package com.jsyso.weixin.api;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jsyso.jsyso.lang.JStringUtils;
import com.jsyso.weixin.utils.Params;
import com.jsyso.weixin.utils.PaymentUtils;
import com.jsyso.weixin.web.InitParams;

public class SnsAPI extends API {

	protected static final String OAUTH2_AUTHORIZE = "/connect/oauth2/authorize?";
	
	public static String getAuthorizeURL(String appId, String redirect_uri, boolean snsapiBase) {
        return getAuthorizeURL(appId, redirect_uri, null, snsapiBase);
    }
	
	public static String getAuthorizeSnsapiBaseURL(String appId, String redirect_uri) {
		return getAuthorizeURL(appId, redirect_uri, null, true);
	}
	
	/**
	 * 生成Authorize链接
	 * @return
	 */
	public static String getAuthorizeURL(String appId, String redirectUri, String state, boolean snsapiBase) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appId);
        params.put("response_type", "code");
        params.put("redirect_uri", redirectUri);
        // snsapi_base（不弹出授权页面，只能拿到用户openid）
        // snsapi_userinfo（弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
        if (snsapiBase) {
            params.put("scope", "snsapi_base");
        } 
        else {
            params.put("scope", "snsapi_userinfo");
        }
        if (StringUtils.isBlank(state)) {
            params.put("state", "wx#wechat_redirect");
        } 
        else {
            params.put("state", state.concat("#wechat_redirect"));
        }
        String para = PaymentUtils.packageSign(params, false);
        return JStringUtils.newBuilder(OPEN_WEIXIN_QQ_COM, OAUTH2_AUTHORIZE, para).toString();
    }
	
	protected static final String OAUTH2_ACCESS_TOKEN = "/sns/oauth2/access_token";
	
	/**
	 * 通过code获取access_token
	 * @return
	 */
	public API oauth2AccessToken(String appid, String secret, String code) {
		this.method = RequestMethod.GET;
		this.getParams = Params.create("appid", appid).put("secret", secret).put("code", code);
		this.url = API_WEIXIN_QQ_COM + OAUTH2_ACCESS_TOKEN;
		return this;
	}
	public API oauth2AccessToken(String appid, String code) {
		this.method = RequestMethod.GET;
		this.getParams = Params.create("appid", appid).put("secret", InitParams.getConfig(appid, "appSecret"))
				.put("code", code).put("grant_type", "authorization_code");
		this.url = API_WEIXIN_QQ_COM + OAUTH2_ACCESS_TOKEN;
		return this;
	}
}
